package ee.battleship.classes;
import java.util.ArrayList;
import java.util.Random;

public class Game {
	private int id;
	private Player p1;
	private Player p2;
	private int whoseTurn; 		// 0 - p1, 1 - p2
	private int status = 0; 	// 0 - game is not started, 1 - game is started, 2 - game is finished, 3 - enemy has left the game
	private int gameHash;
	private Player winner;
	private ArrayList<Player> players = new ArrayList<Player>();
	
	public Game(Player pl1, Player pl2, int _id) {
		this.p1 = pl1;
		this.p2 = pl2;
		this.id = _id;
		Random randomGenerator = new Random();
		whoseTurn = randomGenerator.nextInt(1);
	}
	
	public Game(int id) {
		this(null, null, id);
	}
	
	public int getId() {
		return id;
	}
	
	/* Replaced with getEnemy */
	public Player getOtherPlayer(Player p) {
		if(p1.getId() == p.getId()) {
			return p2;
		}
		return p1;
	}
	
	public void changeTurn() {
		whoseTurn = (whoseTurn == 1) ? 0 : 1;
	}
	
	public boolean isMyTurn(Player player) {
		
		if (getPlayers().size() > 1 && getStatus() == 1) {
			if (player.getId() == getPlayers().get(0).getId()) {
				if (whoseTurn == 0) {
					return true;
				} else {
					return false;
				}
			} else {
				if(whoseTurn == 1) {
					return true;
				}
				else {
					return false;
				}
			}
		}
		
		return false;
	}

	public int getStatus() {
		return status;
	}

	public void setStatus(int status) {
		this.status = status;
	}

	public void addPlayer(Player player) {
		
		if(getPlayers() != null) {
			if (getPlayers().size() < 2) {
				getPlayers().add(player);
			} 
		}
	}
	
	public Player getEnemy(Player player) {
		Player enemy = null;
		
		if (getPlayers().get(0).getId() == player.getId()) {
			enemy = getPlayers().get(1);
		} else {
			enemy = getPlayers().get(0);
		}
		
		return enemy;
	}
	
	public ArrayList<Player> getPlayers() {
		return players;
	}

	public void setPlayers(ArrayList<Player> players) {
		this.players = players;
	}

	public int getGameHash() {
		return gameHash;
	}

	public void setGameHash() {
		Random generator = new Random();
		this.gameHash = generator.nextInt(10000);
	}

	public Player getWinner() {
		return winner;
	}

	public void setWinner(Player winner) {
		this.winner = winner;
	}
	
	public boolean isFinished() {
		if (this.status == 2) {
			return true;
		}
		
		return false;
	}
	
	public boolean hasEnemyLeft() {
		if (this.status == 3) {
			return true;
		}
		
		return false;
	}

}
